#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.common.convert;

import com.alibaba.fastjson.serializer.AfterFilter;
import com.alibaba.fastjson.serializer.PropertyFilter;
import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;

/**
 * Description:
 * OAuth2AccessToken 并不支持 FastJsonHttpMessageConverter，
 * 导致数据格式错误，此类专门用来转换OAuth2AccessToken.
 *
 * @author wupanhua
 * @date 2020-04-22 14:11
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
public class CustomAuth2SerializeFilter extends AfterFilter implements PropertyFilter {

    @Override
    public boolean apply(Object object, String name, Object value) {
        return !(object instanceof DefaultOAuth2AccessToken
                || object instanceof DefaultExpiringOAuth2RefreshToken);
    }

    @Override
    public void writeAfter(Object object) {
        if (object instanceof DefaultOAuth2AccessToken) {
            DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken) object;
            writeKeyValue("access_token", accessToken.getValue());
            writeKeyValue("token_type", accessToken.getTokenType());
            writeKeyValue("refresh_token", accessToken.getRefreshToken().getValue());
            writeKeyValue("expires_in", accessToken.getExpiresIn());
            writeKeyValue("scope", String.join(" ", accessToken.getScope()));
        }
    }
}
